import { createRouter, createWebHashHistory } from 'vue-router'
import { storage } from '@/utils/storage';
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    name: 'login',
    path: '/login',
    component: () => import('@/view/login/index.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    name: 'register',
    path: '/register',
    component: () => import('@/view/register/index.vue'),
    meta: {
      title: '注册'
    }
  },
  {
    name: 'reset-password',
    path: '/reset-password',
    component: () => import('@/view/user/reset-password.vue'),
    meta: {
      title: '重置密码'
    }
  },
  {
    name: 'country-select',
    path: '/country-select',
    component: () => import('@/view/country-select/index.vue'),
    meta: {
      title: '选择国家/地区'
    }
  },
    {
    name: 'home',
    path: '/home',
    component: () => import('@/view/home/index.vue'),
    meta: {
      title: '工作台'
    }
  },

  {
    name: 'organization',
    path: '/organization',
    component: () => import('@/view/organization/index.vue'),
    meta: {
      title: '组织架构'
    }
  },
  {
    name: 'organization-department',
    path: '/organization/department/:id',
    component: () => import('@/view/organization/department.vue'),
    meta: {
      title: '部门详情'
    }
  },
  {
    name: 'organization-add-member',
    path: '/organization/add-member',
    component: () => import('./view/organization/add-member.vue'),
    meta: {
      title: '添加成员'
    }
  },
  {
    path: '/organization/add-department',
    component: () => import('./view/organization/add-department.vue'),
    meta: {
      title: '添加子部门'
    }
  },
  {
    name: 'organization-set-manager',
    path: '/organization/set-manager',
    component: () => import('./view/organization/set-manager.vue'),
    meta: {
      title: '设置部门主管'
    }
  },
   {    name: 'organization-edit-member',    path: '/organization/edit-member/:id',    component: () => import('./view/organization/edit-member.vue'),    meta: {      title: '编辑员工'    }  },  {    name: 'organization-search',    path: '/organization/search',    component: () => import('./view/organization/organization-search.vue'),    meta: {      title: '搜索'    }  },
  {
    name: 'contract-add',
    path: '/contract/add',
    component: () => import('@/view/contract/add.vue'),
    meta: {
      title: '新建合同',
      keepAlive: true
    }
  },
  {
    name: 'expense-add',
    path: '/expense/add',
    component: () => import('@/view/expense/add.vue'),
    meta: {
      title: '费用报销',
      keepAlive: true
    }
  },
  {
    name: 'contract-add-pay',
    path: '/contract/addPay',
    component: () => import('@/view/contract/addPay.vue'),
    meta: {
      title: '付款申请',
      keepAlive: true
    }
  },
  {
    name: 'contract-detail',
    path: '/contract/detail/:id',
    component: () => import('@/view/contract/detail/index.vue'),
    meta: {
      title: '合同详情'
    }
  },
  {
    name: 'expense-detail',
    path: '/expense/detail/:id',
    component: () => import('@/view/expense/detail/index.vue'),
    meta: {
      title: '报销详情'
    }
  },
  {
    name: 'pay-detail',
    path: '/contract/detail/pay-detail/:id',
    component: () => import('@/view/contract/detail/pay-detail.vue'),
    meta: {
      title: '付款详情'
    }
  },
  {
    name: 'ai-assistant',
    path: '/ai-assistant',
    component: () => import('@/view/ai-assistant/index.vue'),
    meta: {
      title: 'AI助手'
    }
  },
  {
    name: 'user-settings',
    path: '/user/settings',
    component: () => import('@/view/user/settings.vue'),
    meta: {
      title: '个人设置'
    }
  },
  {
    name: 'file-preview',
    path: '/file-preview',
    component: () => import('@/view/file-preview/index.vue'),
    meta: {
      title: '文件预览'
    }
  },
  {
    name: 'approvals',
    path: '/approvals',
    component: () => import('@/view/approvals/index.vue'),
    meta: {
      title: '审批中心'
    }
  }
  ,
  {
    name: 'message',
    path: '/message',
    component: () => import('@/view/message/index.vue'),
    meta: {
      title: '公告管理'
    }
  },

]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  const title = to?.meta?.title
  if (title) {
    document.title = title as string
  }

  // 从隔离存储中获取token
  const token = storage.getItem('accessToken')
  const refreshToken = storage.getItem('refreshToken')

  // 白名单路由 - 不需要验证token
  const whiteList = ['/login', '/register', '/country-select','/reset-password']
  
  // 检查用户是否已登录
  const isAuthenticated = token || refreshToken
  
  // 如果用户已登录
  if (isAuthenticated) {
    if (to.path === '/login') {
      // 如果尝试访问登录页，重定向到首页
      next({ 
        path: '/home',
        replace: true,
        force: true  // 强制导航，确保URL更新
      })
      return
    }
    // 已登录用户访问其他页面，允许访问
    next()
    return
  }
  
  // 用户未登录
  if (whiteList.includes(to.path)) {
    // 如果是白名单页面，允许访问
    next()
    return
  }
  
  // 非白名单页面，重定向到登录页
  next({
    path: '/login',
    query: { redirect: to.fullPath },
    replace: true,
    force: true  // 强制导航，确保URL更新
  })
})

// 全局后置守卫：派发导航事件并标记前进/后退方向（基于 history.state.position）
router.afterEach((to, from) => {
  try {
    const s = window.history.state as any;
    const curPos = s && typeof s.position === 'number' ? s.position : null;
    const w = window as any;
    if (typeof w.__lastNavPos === 'undefined') {
      w.__lastNavPos = curPos;
    }
    const lastPos = w.__lastNavPos;
    const isBack = (typeof curPos === 'number' && typeof lastPos === 'number')
      ? (curPos < lastPos)
      : false;
    w.__lastNavPos = curPos;

    window.dispatchEvent(new CustomEvent('router:navigation', {
      detail: { to, from, isBack, position: { curPos, lastPos } }
    }));
  } catch (e) {
    // 守卫中不影响正常导航，仅记录错误
    console.warn('[router.afterEach] 派发导航事件失败:', e);
  }
});

export default router
